import router from './router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/cookies'
import { getStorage, setStorage } from '@/utils/storage'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { usePermissionStore } from '@/store/modules/permission'
const modules = import.meta.glob('./views/**/**.vue')
import Layout from '@/Layout/index.vue'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']
let isAddDynamicMenuRoutes = false
router.beforeEach(async (to: any, from: any, next: Function) => {
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next()
      NProgress.done()
    } else {
      // let userInfo = getStorage('userInfo')
      let routers = getStorage('routers')
      if (!routers) {
        await usePermissionStore().generateRoutes().then(routes => {
          if (isAddDynamicMenuRoutes) {
            next()
          } else {
            let accessRoutes = filterAsyncRouter(routes)
            accessRoutes.forEach((rout: any) => {
              router.addRoute(rout) // 动态添加可访问路由表
            })
            isAddDynamicMenuRoutes = true
            next({ ...to, replace: true })
          }
        })
      } else {
        if (isAddDynamicMenuRoutes) {
          next()
        } else {
          let accessRoutes = filterAsyncRouter(routers)
          accessRoutes.forEach((rout: any) => {
            router.addRoute('layout', rout) // 动态添加可访问路由表
          })
          isAddDynamicMenuRoutes = true
          next({ ...to, replace: true })
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login`)
      NProgress.done()
    }
  }
})
router.afterEach(() => {
  NProgress.done()
})
// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap: any) {
  if (!asyncRouterMap) return []
  return asyncRouterMap.reduce((acc: any, route: any, index: any) => {
    
    if (route.children && route.children.length > 0) {
      // if (route.component == 'Layout') {
        route.component = null
      // }
    } else {
      route.component = modules[`./views/${route.component}`]
    }
    // 如果有子路由，递归添加
    if (route.children && route.children.length > 0) {
      route.children = filterAsyncRouter(route.children)
    }
    acc.push({
      hidden: route.hidden,
      path: route.path,
      children:
        route.children && route.children.length > 0 ? route.children : null,
      meta: {
        title: route.title,
        icon: route.icon,
        visible: route.visible
      },
      component: route.component
    })
    return acc
  }, [])
}


